﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;

namespace UFrame
{
    /// <summary>
    /// 游戏运行时的websocket,一只监听让对方来连接我
    ///
    /// 
    /// </summary>
    public class WebGMControl : MonoBehaviour
    {
        private bool isMonitor = true;
        public string curIP = "127.0.0.1";
        public string port = "9098";

        [HideInInspector] public bool isMonitorLog = false;
        [HideInInspector, NonSerialized] public TcpListener client;

        private BufferVerify bufferVerify = new BufferVerify();
        private static BufferVerify.BufferInfo curBufferInfo = new BufferVerify.BufferInfo();
        private Encoding encoding = Encoding.UTF8;
        public bool isDebug = false;
        public static StringBuilder sb = new StringBuilder();
        private static GUIStyle curStyle = new GUIStyle();
        private NetworkStream tcpStream;
        private Vector2 scroll = new Vector2(0, 0);
        private bool isReceive = true;
        
        public void Awake()
        {
            if (Application.isEditor && string.IsNullOrEmpty(curIP))
                curIP = "127.0.0.1";

            curStyle.fontSize = 22;
            curStyle.normal.textColor = Color.black;
        }

        void Start()
        {
            EventMa.Register<WebGMJson>(WebGMJsonArgs.EventId, OnWeb);
            StartMonitor();
        }


        public void OnApplicationQuit()
        {
            isMonitor = false;
            if (client != null)
            {
                client.Stop();
                //monitor.Dispose();
            }
        }

        public async void StartMonitor()
        {
            client = new TcpListener(IPAddress.Any, Convert.ToInt32(port));
            client.Start();
            var tcpClient = await client.AcceptTcpClientAsync();
            tcpStream = tcpClient.GetStream();
            sb.AppendLine("手机:监听到socket连接过来");
            ReceiveInfo();
        }
        
        public async void ReceiveInfo()
        {
            if (tcpStream != null)
            {
                while (isReceive)
                {
                    byte[] b = new byte[2500];
                    var count = await tcpStream.ReadAsync(b, 0, b.Length);
                    byte[] packAry = new byte[count];
                    Array.Copy(b, 0, packAry, 0, count);
                    curBufferInfo = bufferVerify.ReceiveStream(packAry, curBufferInfo);
                    if (curBufferInfo.isFull)
                    {
                        //发送事件
                        string data = encoding.GetString(curBufferInfo.contentAry, 0, curBufferInfo.contentAry.Length);
                        var obj = JsonUtility.FromJson<WebGMJson>(data);
                        if (obj == null)
                        {
                            //Debug.Log("序列化不成功\n" + data);
                        }

                        EventMa.Notify<WebGMJson>(WebGMJsonArgs.EventId, obj);
                        
                        //开始释放
                        curBufferInfo.Clear();
                    }
                }
            }
        }


        public void Update()
        {
            //PLGUITools.ShowUI(1, s.IsListening);
            //PLGUITools.ShowUI(2, s.Address.ToString());
            //PLGUITools.ShowUI("port: ", s.Port.ToString());
        }


        public void OnGUI()
        {
            if (isDebug)
            {
                scroll = GUILayout.BeginScrollView(scroll);
                GUILayout.TextArea(sb.ToString(), curStyle);
                GUILayout.EndScrollView();

                // EditorGUILayout.BeginScrollView(scroll);
                // EditorGUILayout.TextArea(sb.ToString(), curStyle);
                // EditorGUILayout.EndScrollView();

                //GUILayout.TextArea(sb.ToString(),curStyle);
            }
        }


        public void OnWeb(WebGMJson json)
        {
            if (json.msgId == 0)
            {
                MinCSRef.RunCode(null, json.content);
            }

            if (json.msgId == 1) //日志
            {
                isMonitorLog = !isMonitorLog;
                if (isMonitorLog){
                    Application.logMessageReceived += OnLog;
                    Debug.Log("手机开启监听日志");
                }else{
                    Application.logMessageReceived -= OnLog;
                    Debug.Log("手机取消监听日志");
                }
            }

            if (json.msgId == 10000)
            {
                //serviceIP = json.ip;
            }
            if (json.msgId == 5)
            {
               Debug.Log("收到服务器发送过来的消息: " + json.content);
            }
        }

        private void OnLog(string condition, string stackTrace, LogType type)
        {
            WebGMJson webObj = new WebGMJson();
            webObj.msgId = 1000;
            webObj.content = condition + "  \n" + stackTrace;
            var data = bufferVerify.SendRPC(1, JsonUtility.ToJson(webObj), encoding);
            tcpStream.Write(data, 0, data.Length);
            sb.AppendLine("把日志传送到服务器");
            //Debug.Log("把日志传送到服务器");
        }


    }
}